package com.david.fastmsg.controller;

import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.codec.Base32;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.david.fastmsg.Constant.Param;
import com.david.fastmsg.modal.Users;
import com.david.fastmsg.service.UsersService;
import com.david.fastmsg.utils.NettyConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

@Validated
@Controller
public class MainController {

    @Autowired
    private NettyConfig nettyConfig;

    @Autowired
    private UsersService usersService;

    private static TimedCache<String, String> timedCache;

    static {
        timedCache = new TimedCache<>(3600 * 24 * 1000);
        timedCache.schedulePrune(1000);
    }

    /**
     * <pre>
     *
     * 接口功能： 主入口
     *
     * 接口路径： /
     *
     * </pre>
     * @return
     */
    @GetMapping(value = "/")
    public ModelAndView main() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("main");
        return modelAndView;
    }

    /**
     * <pre>
     *
     * 接口功能： 注册
     *
     * 接口路径： /create
     *
     * 接口描述： 打开注册界面，注册成功后，跳转index
     *
     * </pre>
     * @return
     */
    @GetMapping(value = "/create")
    public ModelAndView create() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("create");
        return modelAndView;
    }


    /**
     * <pre>
     *
     * 接口功能： 主页面
     *
     * 接口路径： /index
     *
     * 接口描述： 主页面，基础信息准备，包好socket的信息
     *
     * </pre>
     * @return
     */
    @GetMapping(value = "/index")
    public ModelAndView index(HttpServletRequest request, @NotNull String url) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        String userId = Base32.decodeStr(url);
        Users user = usersService.findByUserId(userId);
        modelAndView.addObject(Param.USER_ID, user.getUserId());
        modelAndView.addObject(Param.USER_NAME, user.getUserName());
        modelAndView.addObject(Param.USER_CODE, user.getUserCode());
        modelAndView.addObject(Param.SERVER_IP, NetUtil.getLocalhost().getHostAddress() + ":" + nettyConfig.getPort());
        modelAndView.addObject(Param.USER_PIC, user.getPicSmall());
        return modelAndView;
    }

}
